import nedb from './nedb'

export default {
  /**
   * 获取聊天记录
   * @param {String} openid 对应用户的openid
   * @param {int} sort 结果排序 默认升序
   */
  async getChatlog (openid, sort) {
    sort = sort || 1
    try {
      var result = await nedb.chatlog_list.find({
        openid: openid
      })
      if (result.length > 0) { // 获取数据成功
        result.sort(function (v1, v2) {
          if (sort === 1) {
            return v1.send_time - v2.send_time
          } else {
            return v2.send_time - v1.send_time
          }
        })
        return Promise.resolve(result)
      }
      return Promise.resolve([])
    } catch (e) {
      return Promise.resolve([])
    }
  },
  /**
   * 添加聊天记录
   * @param {Object} openid 消息内容
   * Object.prototype.toString.call(data) === '[object Array]'
   * 判断是不是数组
   */
  async addChatlog (data) {
    try {
      var result = await nedb.chatlog_list.find({
        id: data.id,
        openid: data.openid,
        cs_id: data.cs_id
      })
      if (result.length === 0) await nedb.chatlog_list.insert(data)
      return Promise.resolve(data)
    } catch (e) {
      return Promise.resolve(null)
    }
  }
}
